import Vue from 'vue'
import {ADD_CART} from "../actions_type"
import {ADD_COUNT, ADD_TO_CART, CHANGE_IS_CHECKED, IS_SELECT_ALL} from "../mutations_type";
import {CART_LIST_LENGTH, GET_CART_LIST} from "../getters_type"

// 购物车数据
export default {
  state: {
    cartList: [],   //购物车数据
    isSelectAllBool: true,  // 商品全选取反
  },
  getters: {
    // 购物车数据长度length
    [CART_LIST_LENGTH](state){
      return state.cartList.length
    },
    // 返回购物车数据
    [GET_CART_LIST](state){
      return state.cartList
    }
  },
  actions: {
    // 商品添加到购物车
    [ADD_CART](context, product){
      return new Promise((resolve, reject) => {
        const index = context.state.cartList.findIndex(item => item.iid === product.iid );
        if (index === -1) {
          context.commit(ADD_COUNT, product)
          resolve('加入购物车成功')
        } else {
          context.commit(ADD_TO_CART, index)
          resolve('商品数量加1成功')
        }
      })
    }
  },
  mutations: {
    // 新的商品，增加count属性
    [ADD_COUNT](state, product) {
      product.count = 1;
      product.isChecked = true;
      state.cartList.unshift(product)
    },
    // 购物车已有商品，count数量加1
    [ADD_TO_CART](state, index) {
      const product = state.cartList[index];
      product.count += 1;
      state.cartList.splice(index, 1);
      state.cartList.unshift(product);
    },
    // 改变商品是否选中状态
    [CHANGE_IS_CHECKED](state, product){
      const index = state.cartList.findIndex(item => item.iid === product.iid)
      const i = state.cartList.findIndex(item => item.isChecked === false )
      if (i === -1){
        state.isSelectAllBool = true
      } else {
        state.isSelectAllBool = false
      }

      // 必须使用splice或者$set，让数据成为响应式数据
      state.cartList.splice(index, 1, product)
    },

    // 全选，取反
    [IS_SELECT_ALL](state){
      state.isSelectAllBool = !state.isSelectAllBool
      for(var i=0; i<state.cartList.length; i++){
        Vue.set(state.cartList[i], 'isChecked', state.isSelectAllBool)
      }
    }
  }
}
